/**
 * 将数据转换为树形结构
 * @param data
 * @returns
 */
export function arrayToTree(items: any[], parentId: string = '0') {
  const result: any[] = [];
  const itemMap = {};

  // 将所有项存储在一个映射中
  items.forEach((item) => {
    itemMap[item.id] = {
      ...item,
      title: item.name,
      key: item.id,
      label: item.name,
      value: item.code,
      children: [],
    };
  });

  items.forEach((item) => {
    const id = item.id;
    const pid = item.parentId;
    const treeItem = itemMap[id];

    if (pid === parentId) {
      result.push(treeItem);
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = { children: [] };
      }
      itemMap[pid].children.push(treeItem);
    }
  });

  return result;
}
